import React, { useEffect, useState } from 'react';
import { Grid, makeStyles } from '@material-ui/core';
import MainFeaturedPost from './components/MainFeaturedPost';
import FeaturedPost from './components/FeaturedPost';
import Main from './components/Main';

import { getRecommended } from '../../api/actions/article';

const useStyles = makeStyles((theme) => ({
  mainGrid: {
    marginTop: theme.spacing(3),
  },
}));

export default function Home() {
  const classes = useStyles();

  const [bannerPost, setBannerPost] = useState({});
  const [bannerPost2, setBannerPost2] = useState([]);
  const [recommends, setRecommends] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await getRecommended();
        if (res.code === 0) {
          const { data } = res;
          setBannerPost(data.filter((post) => post.recommend === 1)[0] || []);
          setBannerPost2(data.filter((post) => post.recommend === 2) || []);
          setRecommends(data.filter((post) => post.recommend === 0) || []);
        }
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('推荐页面错误:', e);
      }
    };
    fetchData();
  }, []);

  return (
    <>
      <MainFeaturedPost post={bannerPost} />
      <Grid container spacing={4}>
        {bannerPost2.map((post, i) => (
          <FeaturedPost key={i} post={post} />
        ))}
      </Grid>
      <Grid container spacing={5} className={classes.mainGrid}>
        <Main posts={recommends} />
      </Grid>
    </>

  );
}
